package eventservice;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class EventReader {
	
	private ListEventPlace lep;
	private EventAbs event;
	
	public EventReader(){}
	
	public void openList(){
		try {
			lep = ListEventPlace.getInstance();
			File fXmlFile = new File("C://temp/ca.ets.osgi.eventservice/src/eventservice/events.xml");
			//File fXmlFile = new File("C://eclipse/Workspace/ca.ets.osgi.eventservice/src/eventservice/events.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();
			NodeList nodes = doc.getElementsByTagName("Event");
			
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);

				if (node.getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) node;
				int noEvent = Integer.parseInt(getValue("noID",element).trim());
				String name = getValue("nom",element).trim();
				
				if (lep.verifiedInscriptionEventByName(name) == false) {
					Adresse adresse = null;
					NodeList nodeli = doc.getElementsByTagName("adresse");
					int nodemax = nodeli.getLength();
					for (int j = 0; j < nodeli.getLength(); j++) {
						Node nNode = nodeli.item(j); 
						
						if (nNode.getNodeType() == Node.ELEMENT_NODE) {
							Element ele = (Element) node;
							int noAdresse  =Integer.parseInt(getValue("noadresse",ele).trim());
							String rue = getValue("rue",ele).trim();
							String ville = getValue("ville",ele).trim();
							String province = getValue("province",ele).trim();
							String codepostal = getValue("codepostal",ele).trim();
							adresse = new Adresse(noAdresse,rue,ville,province,codepostal);
						}			
					}
					InscriptionEvent iEvent = new InscriptionEvent(name,adresse,getValue("phone",element).trim(),getValue("dateStr",element).trim(),getValue("dateEnd",element).trim(),noEvent);
					iEvent.setAvailablePlace(Integer.parseInt(getValue("place",element)));
					iEvent.setAvailability();
					event = iEvent;
					lep.addEventToTable(name,event);
				}
				
				
				}
				
			}


			
			
		}catch (Exception ex) {
			ex.printStackTrace();
		}
		
		
		
		


	}
	
	private static String getValue(String tag, Element element) {
		NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
		Node node = (Node) nodes.item(0);
		return node.getNodeValue();
	}



}
